from flask import Flask, request, jsonify, send_file, render_template
from hp_sta_v01 import utils, config 
from werkzeug.utils import secure_filename
import glob
import json
import os


template_dir = config.template_dir
static_dir = config.static_dir
app = Flask(__name__, template_folder=template_dir, static_folder=static_dir)

# 载入配置参数
app.config['UPLOAD_FOLDER'] = config.UPLOAD_FOLDER
app.config['TEMP_RESULT_FOLDER'] = config.TEMP_RESULT_FOLDER
app.config['ARCHIVE_FOLDER'] = config.ARCHIVE_FOLDER
app.config['ALLOWED_EXTENSIONS'] = config.ALLOWED_EXTENSIONS
app.config['MAX_CONTENT_LENGTH'] = config.MAX_CONTENT_LENGTH

# 配置参数
app.config['DEFAULT_TOLERANCE'] = 1
app.config['DEFAULT_THRESHOLD'] = 0.6

@app.route('/')
def stats_home():
    return render_template('stats.html')

@app.route('/stats')
def stats():
    return render_template('stats.html')

# 判断文件类型是否合法
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

# 匹配热像素的接口
@app.route('/api/match_hotpixels', methods=['POST'])
def match_hotpixels():
    tolerance = request.args.get('tolerance', default=app.config['DEFAULT_TOLERANCE'], type=int)
    threshold = request.args.get('threshold', default=app.config['DEFAULT_THRESHOLD'], type=float)
    
    if 'files' not in request.files:
        return jsonify({'error': 'No files part'}), 400
    
    files = request.files.getlist('files')
    if not files or all(file.filename == '' for file in files):
        return jsonify({'error': 'No selected files'}), 400

    txt_files = []
    for file in files:
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)
            txt_files.append(filepath)

    if not txt_files:
        return jsonify({'error': 'No valid txt files uploaded'}), 400

    global_index = utils.build_global_index(txt_files, tolerance=tolerance)
    total_files = len(txt_files)
    
    result = {
        'total_files': total_files,
        'tolerance': tolerance,
        'threshold': threshold,
        'matched_pixels': len(global_index)
    }
    return jsonify(result)

# 生成统计报告
@app.route('/api/report', methods=['GET'])
def generate_report():
    tolerance = request.args.get('tolerance', default=app.config['DEFAULT_TOLERANCE'], type=int)
    threshold = request.args.get('threshold', default=app.config['DEFAULT_THRESHOLD'], type=float)
    
    txt_files = glob.glob(os.path.join(app.config['UPLOAD_FOLDER'], '*.txt'))
    total_files = len(txt_files)

    if total_files == 0:
        return jsonify({'error': 'No txt files found in the upload folder'}), 404

    global_index = utils.build_global_index(txt_files, tolerance=tolerance)
    
    report_path = os.path.join(app.config['UPLOAD_FOLDER'], 'temp_report.txt')
    with open(report_path, 'w', encoding='utf-8') as f:
        report_content = utils.generate_report_content(global_index, total_files, tolerance, threshold)
        f.write(report_content)

    return send_file(report_path, as_attachment=True)

@app.route('/api/archive-metadata')
def get_archive_metadata():
    metadata_path = os.path.join(app.config['ARCHIVE_FOLDER'], 'metadata.json')
    if not os.path.exists(metadata_path):
        return jsonify([])
    with open(metadata_path, 'r') as f:
        return jsonify(json.load(f))

@app.route('/api/stats-match')
def stats_match():
    category = request.args.get('category')
    value = request.args.get('value')
    metadata_path = os.path.join(app.config['ARCHIVE_FOLDER'], 'metadata.json')
    if not os.path.exists(metadata_path):
        return jsonify({'labels': [], 'counts': []})

    with open(metadata_path, 'r') as f:
        data = json.load(f)

    filtered = [item for item in data if item.get(category) == value]
    labels = [item['filename'] for item in filtered]
    counts = [item.get('hot_pixel_count', 0) for item in filtered]

    return jsonify({'labels': labels, 'counts': counts})

# 启动服务器
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=6668, debug=True)
